//
//  FKChooseAttrPopVC.m
//  BaiYeMallShop
//
//  Created by Macbook Pro on 2018/12/5.
//  Copyright © 2018 Macbook Pro. All rights reserved.
//

#import "FKChooseAttrPopVC.h"
#import "FKCommoditySpecification.h"
#import "FKChooseAttrCell.h"
#import "FKGoodsOption.h"
#import "FKChooseAttrFooterView.h"
#define kContainerH (fkScreenH * 0.5)
static NSString *const ID = @"FKChooseAttrItemCell";

@interface FKChooseAttrPopVC ()<UITableViewDataSource, UITableViewDelegate, FKChooseAttrCellDelegate>

@property (nonatomic, weak) UIView *container;
// 图片
@property (nonatomic, weak) UIImageView *pictureView;
// 价格
@property (nonatomic, weak) UILabel *priceLabel;
// 库存
@property (nonatomic, weak) UILabel *skuLabel;
// 规格
@property (nonatomic, weak) UILabel *specLabel;

@property (nonatomic, weak) UITableView *tableView;
@property (nonatomic, weak) FKChooseAttrFooterView *footer;
@property (nonatomic, strong) NSArray *datas;

/** 购买数量 */
@property (nonatomic, assign) NSInteger buyNum;
/** 后台返回的规格列表 */
@property (nonatomic, strong) NSArray *specifications;
/** 选中的规格值数组 */
@property (nonatomic, strong) NSMutableArray *selectedSpecValues;
@property (nonatomic, strong) NSArray *options;
@property (nonatomic, strong) FKGoodsOption *selectedOption;

@property (nonatomic, strong) NSMutableArray *titles;

@end

@implementation FKChooseAttrPopVC

- (NSArray *)datas
{
    if (!_datas) {
        _datas = [NSArray array];
    }
    return _datas;
}

- (NSArray *)options
{
    if (!_options) {
        _options = [NSArray array];
    }
    return _options;
}

- (NSMutableArray *)selectedSpecValues
{
    if (!_selectedSpecValues) {
        _selectedSpecValues = [NSMutableArray array];
    }
    return _selectedSpecValues;
}

- (instancetype)init
{
    FKChooseAttrPopVC *vc = [super init];
    // 防止presentViewController过后控制器的view的背景色变成黑色
    vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    vc.buyNum = 1;
    return vc;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor clearColor];
    
    UIView *bgView = [[UIView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:bgView];
    bgView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    [bgView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(close)]];
    
    UIView *container = [[UIView alloc] initWithFrame:CGRectMake(0, fkScreenH, fkScreenW, kContainerH)];
    [self.view addSubview:container];
    self.container = container;
    container.backgroundColor = [UIColor whiteColor];
    
    // 头部
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, fkScreenW, fk_adjustW(95))];
    [container addSubview:topView];
    
    CGFloat pictureWH = fk_adjustW(105);
    CGFloat pictureY = topView.fk_height - pictureWH - 12;
    UIImageView *pictureView = [[UIImageView alloc] initWithFrame:CGRectMake(10, pictureY, pictureWH, pictureWH)];
    [topView addSubview:pictureView];
    self.pictureView = pictureView;
    [pictureView fk_viewCornerRadius:10 borderWidth:0.8 borderColor:fkBgColor];
    
    UILabel *priceLabel = [UILabel fk_labelWithFont:fk_adjustFont(18) textColor:fkMainColor];
    [topView addSubview:priceLabel];
    self.priceLabel = priceLabel;
    
    UILabel *skuLabel = [UILabel fk_labelWithFont:fk_adjustFont(12) textColor:fkColor666666];
    [topView addSubview:skuLabel];
    self.skuLabel = skuLabel;
    
    UILabel *specLabel = [UILabel fk_labelWithFont:fk_adjustFont(12) textColor:fkColor333333 text:@"请选择 规格"];
    [topView addSubview:specLabel];
    self.specLabel = specLabel;
    
    UIButton *closeBtn = [UIButton fk_btnWithTarget:self action:@selector(close) img:[UIImage imageNamed:@"goods_specs_error"]];
    [topView addSubview:closeBtn];
    [closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-10);
        make.top.offset(10);
    }];
    
    UIView *separator = [UIView fk_lineWithFrame:CGRectMake(0, topView.fk_bottom - 0.8, fkScreenW, 0.8)];
    [topView addSubview:separator];
    
    [priceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(pictureView.mas_right).offset(10);
//        make.top.equalTo(pictureView).offset(fk_adjustW(8));
        make.top.offset(fk_adjustW(8));
        make.right.offset(-12);
    }];
    [skuLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(priceLabel);
        make.centerY.offset(0);
    }];
    [specLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(priceLabel);
        make.bottom.offset(fk_adjustW(-8));
    }];
    
    // 底部的确定按钮
    UIButton *confirmBtn = [UIButton fk_btnWithTarget:self action:@selector(confirmBtnClicked) font:fk_adjustFont(18) normalTitle:@"确定" normalTitleColor:[UIColor whiteColor] selectedTitle:nil selectedTitleColor:nil normalImg:nil selectedImg:nil bgImg:[UIImage fk_imageWithColor:fkMainColor] selectedBgImg:nil];
    [container addSubview:confirmBtn];
    [confirmBtn fk_viewCornerRadius:5 borderWidth:0 borderColor:nil];
    [confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(12);
        make.right.offset(-12);
        make.bottom.offset(-10);
        make.height.mas_equalTo(fk_adjustW(44));
    }];
    
    CGFloat tableY = topView.fk_bottom;
    CGFloat tableH = kContainerH - tableY - fk_adjustW(44) - 10;
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, tableY, fkScreenW, tableH)];
    [container addSubview:tableView];
    self.tableView = tableView;
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.tableFooterView = [UIView new];
    tableView.separatorInset = UIEdgeInsetsMake(0, 12, 0, 12);
    FKChooseAttrFooterView *footer = [[FKChooseAttrFooterView alloc] initWithFrame:CGRectMake(0, 0, fkScreenW, fk_adjustW(68))];
    tableView.tableFooterView = footer;
    self.footer = footer;
//    tableView.shouldIgnoreScrollingAdjustment = true;
    
    // 设置初始的价格和库存
    NSMutableAttributedString *priceAttr1 = [@"￥" fk_addAttr:fkMainColor font:fk_adjustFont(13)];
    NSMutableAttributedString *priceAttr2 = [self.data[@"price"] fk_addAttr:fkMainColor font:fk_adjustFont(18)];
    NSMutableAttributedString *priceAttr3 = [fkFORMAT(@" 省￥%@", self.data[@"commission_price"]) fk_addAttr:fkMainColor font:fk_adjustFont(12)];
    [priceAttr1 appendAttributedString:priceAttr2];
    if ([FKCacheTool isMember]) [priceAttr1 appendAttributedString:priceAttr3];

    self.priceLabel.attributedText = priceAttr1;
    self.skuLabel.text = fkFORMAT(@"库存: %@", self.data[@"inventory"]);
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [UIView animateWithDuration:0.25 animations:^{
        CGFloat containerY = fkScreenH - kContainerH;
        self.container.frame = CGRectMake(0, containerY, fkScreenW, kContainerH);
    }];
    
    // 加载数据
    [self.pictureView sd_setImageWithURL:[NSURL URLWithString:self.data[@"img"]] placeholderImage:kPlaceholder_1x1];
//    self.priceLabel.text = fkFORMAT(@"￥%@", firstSpec.price);
//    self.skuLabel.text = fkFORMAT(@"库存: %@", firstSpec.inventory);
    
    [self loadData];
}

#pragma mark - target
- (void)confirmBtnClicked
{
    [self.view endEditing:true];
    
    if (self.selectedSpecValues.count != self.specifications.count) {
        // 正常情况下，永远都不会执行这句代码
        [SVProgressHUD showInfoWithStatus:@"请选择商品规格"];
    }
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"goods_id"] = self.data[@"id"];
    param[@"option_id"] = self.selectedOption.id;
    param[@"nums"] = fkFORMAT(@"%zd", self.buyNum);
    
    if (self.confirmBlock) {
        self.confirmBlock(param);
    }
    [self close];
}

- (void)close
{
    [UIView animateWithDuration:0.25 animations:^{
        self.container.frame = CGRectMake(0, fkScreenH, fkScreenW, kContainerH);
    } completion:^(BOOL finished) {
        [self dismissViewControllerAnimated:false completion:nil];
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.datas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *item = self.datas[indexPath.row];
    FKTableCell *cell = [FKTableCell cellWith:tableView className:item[@"cellName"]];
    cell.data = item[@"data"];
    cell.delegate = self;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *item = self.datas[indexPath.row];
    return [item[@"cellH"] floatValue];
}

#pragma mark - FKChooseAttrCellDelegate
- (void)chooseAttrCell:(FKChooseAttrCell *)cell didSelectedSpecValue:(FKGoodsSpecificationValue *)specValue
{
    if (self.selectedSpecValues.count == 0) {
        [self.selectedSpecValues addObject:specValue];
    } else {
        BOOL added = false;
        for (FKGoodsSpecificationValue *valueItem in self.selectedSpecValues) {
            NSInteger index = [self.selectedSpecValues indexOfObject:valueItem];
            if ([specValue.spec_id isEqualToString:valueItem.spec_id]) { // 有同一个规格的值就直接覆盖
                [self.selectedSpecValues replaceObjectAtIndex:index withObject:specValue];
                added = true;
                break;
            }
        }
        if (!added) [self.selectedSpecValues addObject:specValue];
    }
    
    if (self.specifications.count == self.selectedSpecValues.count) { // 每个规格都选了一个值
        FKGoodsOption *option = [self getOption];
        self.selectedOption = option;
//        self.priceLabel.text = fkFORMAT(@"￥%@", option.marketprice);
//        self.priceLabel.attributedText = [self.priceLabel.text fk_addAttributeStyle:@"￥" color:fkMainColor font:fk_adjustFont(12)];
        NSMutableAttributedString *priceAttr1 = [@"￥" fk_addAttr:fkMainColor font:fk_adjustFont(13)];
        NSMutableAttributedString *priceAttr2 = [option.marketprice fk_addAttr:fkMainColor font:fk_adjustFont(18)];
        NSMutableAttributedString *priceAttr3 = [fkFORMAT(@" 省￥%@", self.data[@"commission_price"]) fk_addAttr:fkMainColor font:fk_adjustFont(12)];
        [priceAttr1 appendAttributedString:priceAttr2];
        if ([FKCacheTool isMember]) [priceAttr1 appendAttributedString:priceAttr3];
        self.priceLabel.attributedText = priceAttr1;
        
        self.skuLabel.text = fkFORMAT(@"库存%@件", option.stock);
        self.specLabel.text = fkFORMAT(@"已选择: %@", option.title);
        self.footer.storeCount = option.stock;
    }
}

// 找到对应的option
- (FKGoodsOption *)getOption
{
    NSMutableArray *valueIds = [NSMutableArray array];
    for (FKGoodsSpecificationValue *value in self.selectedSpecValues) {
        [valueIds addObject:value.id];
    }
    
    for (FKGoodsOption *option in self.options) {
        NSInteger temp = 0;
        for (NSString *valueId in valueIds) {
            if ([option.specArray containsObject:valueId]) {
                temp++;
            }
        }
        if (temp == valueIds.count) {
            return option;
        }
    }
    return nil;
}

#pragma mark - 网络请求
- (void)loadData
{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"item_id"] = self.data[@"id"];
    [FKHttpTool postWithSuffix:@"m=Home&c=Item&a=spec" param:param success:^(FKBaseResult *result) {
        if (result.isSuccess) {
            
            NSMutableArray *datas = [NSMutableArray array];
            
            self.options = [FKGoodsOption mj_objectArrayWithKeyValuesArray:result.data[@"option"]];
            
            NSArray *specifications = [FKCommoditySpecification mj_objectArrayWithKeyValuesArray:result.data[@"spec"]];
            self.specifications = specifications;
            if (specifications.count > 0) {
                // 计算cell的高度
                CGFloat margin = 12;
                for (FKCommoditySpecification *specification in specifications) {
                    NSMutableDictionary *attrItem = [NSMutableDictionary dictionary];
                    [datas addObject:attrItem];
                    attrItem[@"cellName"] = @"FKChooseAttrCell";
                    attrItem[@"data"] = specification;
                    
                    CGFloat cellH = fk_adjustW(46);
                    CGFloat itemRight = 12;
                    for (FKGoodsSpecificationValue *specValue in specification.value) {
                        NSInteger i = [specification.value indexOfObject:specValue];
                        if (i == 0) {
                            itemRight += specValue.itemSize.width;
                            cellH += (fk_adjustW(32) + fk_adjustW(15));
                        } else {
                            itemRight += (margin + specValue.itemSize.width);
                            
                            if (itemRight > fkScreenW) {
                                itemRight = 12;
                                cellH += (margin + fk_adjustW(36));
                            }
                        }
                    }
                    attrItem[@"cellH"] = @(cellH);
                }
            }
            
            self.datas = datas;
            [self.tableView reloadData];
        }
    } failure:nil];
}


@end
